<?php
/**
 * Created by PhpStorm.
 * User: 户学
 * Date: 2018/4/24
 * Time: 11:26
 */

require_once dirname(dirname(dirname(dirname(dirname((__FILE__))))))."/api/linepay/weixin/lib/WxPay.Api.php";
require_once dirname(dirname(dirname(dirname(dirname((__FILE__)))))).'/api/linepay/weixin/example/WxPay.JsApiPay.php';
require_once dirname(dirname(dirname(dirname(dirname((__FILE__)))))).'/api/linepay/weixin/lib/WxPay.Config.php';
require_once dirname(dirname(dirname(dirname(dirname((__FILE__)))))).'/api/linepay/weixin/example/log.php';
//require_once  dirname(dirname(dirname((__FILE__))))."/".'api/linepay/weixin/example/log.php';


class Home extends M_Controller
{
    public function index()
    {

        if (IS_POST) {
            $name = $this->input->get_post('name');
            $class = $this->input->get_post('grade');
            $code = $this->input->get_post('code');
            $subject = $this->input->get_post('subject');
            $phone = $this->input->get_post("phone");
            $remark = $this->input->get_post("remark");
            $remaker_type = $this->input->get_post("remarke_type");
            if (!$name) {
                $error = array('name' => 'code', 'msg' => fc_lang('姓名不能为空'));
            }
            if (!$class) {
                $error = array('name' => 'code', 'msg' => fc_lang('年级不能为空'));
            }
            if (!$subject) {
                $error = array('name' => 'code', 'msg' => fc_lang('科目不能为空'));
            }
            if (!$phone) {
                $error = array('name' => 'code', 'msg' => fc_lang('手机号码不能为空'));
            }

            if (!$remark) {
                $remark = '活动2018';
            }
            //拿到发送的真实验证码
            $where['phone'] = $phone;
            $where['is_last'] = 1;
            $rescode = $this->db->where($where)->order_by('id desc')->get('sms_code')->row_array();


            if ($code == $rescode['code']) {
                $data = array("name" => $name, "grade" => $class, "subject" => $subject, "mobile" => $phone, "remark" => $remark, "addtime" => date('Y-m-d H:i:s', time()));
                $id = $this->db->insert("try_apply", $data);

                if ($id) {
                    $memo = '';
                    if ($remaker_type == 1) {
                        $memo = ACTIVITY_TYPE_1;
                    } else if ($remaker_type == 2) {
                        $memo = ACTIVITY_TYPE_2;
                    }
                    $ecArr = array("f_name" => $name, "f_mobile" => $phone, "81157087" => $class, "81157089" => $subject, "optUserId" => "7173319", "f_memo" => $memo, "81157096" => '免费试听',
                        "customFieldMapping" => array(
                            "81157087" => array("option" => '', "type" => "1"),
                            "81157089" => array("option" => '', "type" => '1'),
                            "81157096" => array("option" => '', "type" => '4')
                        ));
                    $apps = array("appId" => APP_ID, "appSecret" => APP_SECRET);
                    $arrs = ec_getToken(EC_GET_TOKEN, json_encode($apps));
                    $tok = json_decode($arrs, true);
                    $token = $tok['data']['accessToken'];
                    ec_getData(EC_REGISTER_URL, json_encode($ecArr), array("Authorization:$token", "CORP_ID:" . CORP_ID));

                    exit($this->callback_json(array(
                        "status" => 1,
                        "backurl" => '/',
                        'msg' => 'ok',
                        'code' => "<div class='success-poup-box'><div class='box-contect1'>报名成功</div><div class='box-contect2'>我们会尽快与您联系，谢谢！</div></div>",
                        'uid' => $id
                    )));
//                    echo "报名成功";
//                    exit;
                }
            } else {
                echo "验证码填写错误";
                exit;
            }
        }
    }


    public function check_mobile_code(){
        $phone = $this->input->get_post('mobile');
        $code = $this->input->get_post('code');

        $where = array();
        $where['phone'] = $phone;
        $where['is_last'] = 1;

        if(empty($phone)){
            exit;
        }
        if(empty($code)){
            exit;
        }

        $result = $this->db->where($where)->order_by('id desc')->get('sms_code')->row_array();
        //print_r($result);
        $arr = array();
        if($result['code'] == $code){
            $arr['status'] = 1;
            echo json_encode($arr);exit;
        }else{
            $arr['status'] = 0;
            echo json_encode($arr);exit;
        }
    }

    public function activity(){
        if(IS_POST){
            $name = $this->input->get_post('name');
            $class = $this->input->get_post('grade');
            $subject = $this->input->get_post('subject');
            $phone = $this->input->get_post("phone");
            $remark = $this->input->get_post("remark");
            $remaker_type = $this->input->get_post("remarke_type");
            if(!$name){
                $error = array('name' => 'code', 'msg' => fc_lang('姓名不能为空'));
            }
            if(!$class){
                $error = array('name' => 'code', 'msg' => fc_lang('年级不能为空'));
            }
            if(!$subject){
                $error = array('name' => 'code', 'msg' => fc_lang('科目不能为空'));
            }
            if(!$phone){
                $error = array('name' => 'code', 'msg' => fc_lang('手机号码不能为空'));
            }
            if(!$remark){
                $remark = '活动';
            }
            $data = array("name"=>$name,"grade"=>$class,"subject"=>$subject,"mobile"=>$phone,"remark"=>$remark,"addtime"=>date('Y-m-d H:i:s',time()));
            $id = $this->db->insert("try_apply", $data);
            if($id){
                $memo = '';
                if($remaker_type == 1){
                    $memo = ACTIVITY_TYPE_1;
                }else if($remaker_type == 2){
                    $memo = ACTIVITY_TYPE_2;
                }
                $ecArr = array("f_name"=>$name,"f_mobile"=>$phone,"81157087"=> $class,"81157089"=>$subject,"optUserId"=>"7173319","f_memo"=>$memo,"81157096"=>'免费试听',
                    "customFieldMapping"=>array(
                        "81157087"=>array("option"=>'',"type"=>"1"),
                        "81157089"=>array("option"=>'',"type"=>'1'),
                        "81157096"=>array("option"=>'',"type"=>'4')
                    ));
                $apps = array("appId"=>APP_ID, "appSecret"=>APP_SECRET);
                $arrs  = ec_getToken(EC_GET_TOKEN,json_encode($apps));
                $tok = json_decode($arrs,true);
                $token = $tok['data']['accessToken'];
                ec_getData(EC_REGISTER_URL, json_encode($ecArr),array("Authorization:$token", "CORP_ID:".CORP_ID));

                exit($this->callback_json(array(
                    "status"=>1,
                    "backurl"=>'/',
                    'msg' => 'ok',
                    'code' => "<div class='success-poup-box'><div class='box-contect1'>报名成功</div><div class='box-contect2'>我们会尽快与您联系，谢谢！</div></div>",
                    'uid' => $id
                )));
            }

            exit($this->callback_json(array(
                'msg' => $error['msg'],
                'code' => 0
            )));
            if (IS_AJAX) {
                $error && exit(dr_json(0, $error['msg']));
                $id > 0 && exit(json_encode(array(
                    'status' => 1,
                    'backurl' => $back_url,
                    'syncurl' => dr_member_sync_url($code))));
            }
            $code && $this->member_msg(fc_lang('报名成功').$code, $back_url, 1, 3);
            exit;
        }
        $this->template->display("../mobile/index488.html");
    }
    public function m_source(){
        if(IS_POST) {
            $name = $this->input->get_post('name');
            $class = $this->input->get_post('grade');
            $code = $this->input->get_post('code');
            $subject = $this->input->get_post('subject');
            $phone = $this->input->get_post("phone");
            $remark = $this->input->get_post("remark");
            $remaker_type = $this->input->get_post("remarke_type");
            if (!$name) {
                $error = array('name' => 'code', 'msg' => fc_lang('姓名不能为空'));
            }
            if (!$class) {
                $error = array('name' => 'code', 'msg' => fc_lang('年级不能为空'));
            }
            if (!$subject) {
                $error = array('name' => 'code', 'msg' => fc_lang('科目不能为空'));
            }
            if (!$phone) {
                $error = array('name' => 'code', 'msg' => fc_lang('手机号码不能为空'));
            }
            if (!$remark) {
                $remark = '活动未标记';
            }
            $source = "帮帮平台";

            //拿到发送的真实验证码
            $where['phone'] = $phone;
            $where['is_last'] = 1;
            $rescode = $this->db->where($where)->order_by('id desc')->get('sms_code')->row_array();

            if ($code == $rescode['code']) {
                $data = array("name" => $name, "grade" => $class, "subject" => $subject, "mobile" => $phone,"source"=>$source, "remark" => $remark, "addtime" => date('Y-m-d H:i:s', time()));
                $id = $this->db->insert("try_apply", $data);

                if ($id) {
                    $memo = '';
                    if ($remaker_type == 1) {
                        $memo = ACTIVITY_TYPE_1;
                    } else if ($remaker_type == 2) {
                        $memo = ACTIVITY_TYPE_2;
                    }
                    $ecArr = array("f_name" => $name, "f_mobile" => $phone, "81157087" => $class, "81157089" => $subject, "optUserId" => "7173319", "f_memo" => $memo, "81157096" => '免费试听',
                        "customFieldMapping" => array(
                            "81157087" => array("option" => '', "type" => "1"),
                            "81157089" => array("option" => '', "type" => '1'),
                            "81157096" => array("option" => '', "type" => '4')
                        ));
                    $apps = array("appId" => APP_ID, "appSecret" => APP_SECRET);
                    $arrs = ec_getToken(EC_GET_TOKEN, json_encode($apps));
                    $tok = json_decode($arrs, true);
                    $token = $tok['data']['accessToken'];
                    ec_getData(EC_REGISTER_URL, json_encode($ecArr), array("Authorization:$token", "CORP_ID:" . CORP_ID));

                    exit($this->callback_json(array(
                        "status" => 1,
                        "backurl" => '/',
                        'msg' => 'ok',
                        'code' => "<div class='success-poup-box'><div class='box-contect1'>报名成功</div><div class='box-contect2'>我们会尽快与您联系，谢谢！</div></div>",
                        'uid' => $id
                    )));
//                    echo "报名成功";
//                    exit;
                }
            } else {
                echo "验证码填写错误";
                exit;
            }
        }
    }

    public function dockingsrc(){
        $file = WEBPATH.'cache/index/'.(IS_MOBILE ? 'mobile-' : '').DOMAIN_NAME.'-gw_mobile-'.max(intval($_GET['page']), 1).'.html';
//        var_dump(defined('SYS_AUTO_CACHE') && SYS_AUTO_CACHE && SYS_CACHE_INDEX && !is_file($file) && !SITE_CLOSE);exit;
        $this->db->where("client","移动端");
        $this->db->where("is_del",1);
        $this->db->where("is_ground",1);
        if(defined('SYS_AUTO_CACHE') && SYS_AUTO_CACHE && SYS_CACHE_INDEX && !is_file($file) && !SITE_CLOSE){
            ob_start();
            $this->template->assign(array(
                "banners"=>$this->db->where("part","首页")->order_by('sort asc')->get("banner_manage")->result_array(),
                '_indexMobile'=>1,
                'meta_title' => SITE_TITLE,
                'meta_keywords' => SITE_KEYWORDS,
                'meta_description' => SITE_DESCRIPTION,
            ));
            $this->template->display("../mobile/m_source.html");
            $html = ob_get_clean();
            @file_get_contents($file,$html,LOCK_EX);
            echo $html;exit;
        }else{
            $this->template->assign(array(
                "banners"=>$this->db->where("part","首页")->order_by('sort asc')->get("banner_manage")->result_array(),
                '_indexMobile' => 1,
                'meta_title' => SITE_TITLE,
                'meta_keywords' => SITE_KEYWORDS,
                'meta_description' => SITE_DESCRIPTION,
            ));
            $this->template->display("../mobile/m_source.html");
        }
    }
    public function startschool(){
        $this->template->display("../mobile/m_startschool.html");
    }
    public function sexteenclassactivity(){
        $this->template->display("../mobile/m_16class_activity.html");
    }
    public function wholesemester(){
        $this->template->display("../mobile/m_wholesemester_activity.html");
    }
    public function gift(){
        $this->template->display("../mobile/m_gift_activity.html");
    }
    public function giftOrderPage(){
        $this->template->display("../mobile/m_giftorder_activity.html");
    }
    public function sixone(){
        $this->template->display("../mobile/m_61_activity.html");
    }
    public function fatherday(){
        $this->template->display("../mobile/m_father_day_activity.html");
    }
    public function dragon_boat(){
        $this->template->display("../mobile/m_dragon_boat_festival_activity.html");
    }
    public function wei_bo(){
        if(IS_POST){
            $name = $this->input->get_post('name');
            $phone = $this->input->get_post("phone");
            $remark = $this->input->get_post("remark");
            $remaker_type = $this->input->get_post("remarke_type");
            if(!$name){
                $error = array('name' => 'code', 'msg' => fc_lang('姓名不能为空'));
            }
            if(!$phone){
                $error = array('name' => 'code', 'msg' => fc_lang('手机号码不能为空'));
            }
//            if(!$phone_code){
//                $error = array('name' => 'code', 'msg' => fc_lang('验证码不能为空'));
//            }
            if(!$remark){
                $remark = '活动5.6 -6.6';
            }
            $data = array("name"=>$name,"mobile"=>$phone,"remark"=>$remark,"addtime"=>date('Y-m-d H:i:s',time()));
            $id = $this->db->insert("try_apply", $data);
            if($id){
                $memo = '';
                if($remaker_type == 1){
                    $memo = ACTIVITY_TYPE_1;
                }else if($remaker_type == 2){
                    $memo = ACTIVITY_TYPE_2;
                }
                $ecArr = array("f_name"=>$name,"f_mobile"=>$phone,"optUserId"=>"7173319","f_memo"=>$memo,"81157096"=>'免费试听',
                    "customFieldMapping"=>array(
                        "81157087"=>array("option"=>'',"type"=>"1"),
                        "81157089"=>array("option"=>'',"type"=>'1'),
                        "81157096"=>array("option"=>'',"type"=>'4')
                    ));
                $apps = array("appId"=>APP_ID, "appSecret"=>APP_SECRET);
                $arrs  = ec_getToken(EC_GET_TOKEN,json_encode($apps));
                $tok = json_decode($arrs,true);
                $token = $tok['data']['accessToken'];
                ec_getData(EC_REGISTER_URL, json_encode($ecArr),array("Authorization:$token", "CORP_ID:".CORP_ID));

                exit($this->callback_json(array(
                    "status"=>1,
                    "backurl"=>'/',
                    'msg' => 'ok',
                    'code' => "<div class='success-poup-box'><div class='box-contect1'>报名成功</div><div class='box-contect2'>我们会尽快与您联系，谢谢！</div></div>",
                    'uid' => $id
                )));
            }

            exit($this->callback_json(array(
                'msg' => $error['msg'],
                'code' => 0
            )));
            if (IS_AJAX) {
                $error && exit(dr_json(0, $error['msg']));
                $id > 0 && exit(json_encode(array(
                    'status' => 1,
                    'backurl' => $back_url,
                    'syncurl' => dr_member_sync_url($code))));
            }
            $code && $this->member_msg(fc_lang('报名成功').$code, $back_url, 1, 3);
            exit;
        }
        $this->template->display("../mobile/m_weibo.html");
    }


    public function addGift()
    {
            $name = $this->input->get_post('name');
            $code = $this->input->get_post('phcode');
            $phone = $this->input->get_post("phone");
            $addr = $this->input->get_post("addr");
            $remark = $this->input->get_post("remark");
            $remaker_type = $this->input->get_post("remarke_type");

            if (!$remark) {
                $remark = '活动2018';
            }
            //拿到发送的真实验证码
            $where['phone'] = $phone;
            $where['is_last'] = 1;
            $rescode = $this->db->where($where)->order_by('id desc')->get('sms_code')->row_array();

//          if ($code == $rescode['code']) {
            if (true) {

                //存储信息
                $data = array("name" => $name,"addr"=>$addr, "mobile" => $phone, "remark" => $remark,"grade" => '无', "subject" => '无', "addtime" => date('Y-m-d H:i:s', time()));
                $this->db->insert("try_apply", $data);

                $jsApiParameters = $this->pay();


                $this->template->assign(array(
                    'mobile'=>$phone,
                    'jsApiParameters'=>$jsApiParameters,
                ));
                $this->template->display("../mobile/m_giftorder_activity.html");

            }else{
                echo "验证码填写错误";
                exit;
            }

    }

    public function pay(){
        //初始化日志
        $logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
        $log = Log::Init($logHandler, 15);
        //打印输出数组信息
        function printf_info($data)
        {
            foreach($data as $key=>$value){
                echo "<font color='#00ff55;'>$key</font> :  ".htmlspecialchars($value, ENT_QUOTES)." <br/>";
            }
        }
        //①、获取用户openid
        try{
            $tools = new JsApiPay();
            $openId = $tools->GetOpenid();

            //②、统一下单
            $input = new WxPayUnifiedOrder();
            $input->SetBody("hxhd");
            $input->SetAttach("test");
            $orderno = "hxad".date(YmdHis);
            $input->SetOut_trade_no($orderno);
            $input->SetTotal_fee("1");
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 600));
            $input->SetGoods_tag("jsq");
            $input->SetNotify_url(SITE_DOMAIN."/api/linepay/weixin/example/notify.php");
            $input->SetTrade_type("JSAPI");
            $input->SetOpenid($openId);
            $order = WxPayApi::unifiedOrder($input);
            $jsApiParameters = $tools->GetJsApiParameters($order);

            //获取共享收货地址js函数参数
            $editAddress = $tools->GetEditAddressParameters();

            return $jsApiParameters;
        } catch(Exception $e) {
            Log::ERROR(json_encode($e));
        }
    }


}